const mongoose = require('mongoose');


mongoose.connect('mongodb://127.0.0.1:27017/users');

//建议用once连接数据库 once 只链接一次
mongoose.connection.once('open',() => {
    //创建文档（表）的结构
    let mySonSchema = mongoose.Schema({
        //名字必填
        name:{
            type:String,
            //不为空
            required:true,
            //唯一值
            unique:true
        },
        age:Number,
        gender:{
            type:String,
            enum:['男','女'], //设置值必须是数组中的
        },
        hobby:{
            type:Array,
            default:['导管']
        },

    });
    //创建模板对象
    let mySonModel = mongoose.model('mysons',mySonSchema);

    //插入文档
    mySonModel.create({
        name:'张佳',
        age:18,
        gender:'男'
    } ,(err,data) => {
        if (err) {
            console.log(err);
            return;
        }
        console.log(data);
        //断开连接
        mongoose.disconnect();
    });
});
mongoose.connection.on('close',() => {
    console.log('连接关闭');
});
mongoose.connection.on('error',() => {
    console.log('连接失败');
});